package com.wanxi.dangdang.receiver;

import com.alibaba.fastjson.JSONObject;
import com.wanxi.dangdang.model.pojo.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@RabbitListener(queues = {"LeaveQueue"})
@Slf4j
public class MessageReceiver {

    @Autowired
    private JavaMailSender javaMailSender;

    @RabbitHandler
    public void process(String msg) {
        try {
            Message message = JSONObject.parseObject(msg, Message.class);
            log.debug("这是从amqp 取得的信息：{}",msg);
            send(message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void send(Message message) {
        try {
            // 构建一个邮件对象
            SimpleMailMessage mail = new SimpleMailMessage();
            mail.setSubject(message.getSubject());
            // 设置邮件发送者，这个跟application.yml中设置的要一致
            mail.setFrom("1191130313@qq.com");
            // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
            String[] user = new String[]{};
            user = message.getToUsers().toArray(user);
            mail.setTo(user);
            // 设置邮件发送日期
            mail.setSentDate(new Date());
            // 设置邮件的正文
            mail.setText(message.getText());
            // 发送邮件
            javaMailSender.send(mail);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
